package com.hospital.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hospital.system.dao.UserDao;
import com.hospital.system.entity.Role;
import com.hospital.system.entity.User;
import com.hospital.system.entity.UserRole;
import com.hospital.system.service.UserService;
import com.hospital.util.DataGridView;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserDao userDao;
	@Override
	public User findUserByLoginname(String loginname) {
		User user = userDao.selectUserByLoginname(loginname);
		return user;
	}
	@Override
	public List<User> selectAllUser(User user) {
		return userDao.selectAllUser(user);
	}
	@Override
	public int addUser(User user) {
		return userDao.addUser(user);
	}
	@Override
	public int updateUser(User user) {
		return userDao.updateUser(user);
	}
	@Override
	public void deleteUser(Integer user_id) {
		//根据id删除用户
		userDao.deleteUserById(user_id);
		//根据id删除该用户所拥有的角色   中间表
		userDao.deleteRoleUserById(user_id);
	}
	@Override
	public DataGridView queryUserRole(Integer user_id) {
		//按照用户id查询角色
        Integer uid=user_id;
        //先查询所有角色
        List<Role> allRole = userDao.queryAllRole();
        //按照用户id查询角色
        List<Role> userRole = userDao.queryRoleById(uid);
        //如果allRole角色的id与userRole角色的id相等那么可以查询该用户已有的角色 复选框为true
        List<Map<String,Object>> data=new ArrayList<>();
        for (Role r1 : allRole) {
            Boolean LAY_CHECKED = false;
            for (Role r2 : userRole) {
                if (r1.getRole_id() == r2.getRole_id()) {
                    LAY_CHECKED = true;
                }
            }
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("role_id", r1.getRole_id());
            map.put("role_name", r1.getRole_name());
            map.put("role_desc", r1.getRole_desc());
            map.put("LAY_CHECKED", LAY_CHECKED);
            data.add(map);
        }
            return new DataGridView(data);
	}
	@Override
	public void saveUserRole(UserRole userRole) {
		Integer user_id=userRole.getUser_id();
	     Integer[] role_ids=userRole.getRole_ids();
	        userDao.deleteRoleUserById(user_id);
	        //循环添加用户分配的角色
	        if(role_ids!=null&&role_ids.length>0){
	            for(Integer role_id:role_ids){
	            	userDao.insertUserRole(user_id,role_id);
	            }
	        }
	}
	@Override
	public User findUserByLoginUser_id(Integer user_id) {
		return userDao.findUserByLoginUserid(user_id);
	}
	@Override
	public int editLogin(User user) {
		return userDao.updateLoginUser(user);
	}
	@Override
	public int editPwd(User user) {
		return userDao.editPwd(user);
	}
	
}
